package com.wto;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.mysql.fabric.xmlrpc.base.Data;

public class ParseTeacherHtml implements ParseHtml
{
	 private String cookie = "";
	 private CollegeBean collegeBean=null;
	 private String college_url;
	 private Map<String, TeacherBean> teacherMap=new HashMap<String, TeacherBean>();
	 private Map<String, TermBean> termMap=new HashMap<String, TermBean>();
	 public int CODE_ERROR=0;
	   
		public ParseTeacherHtml(CollegeBean collegeBean)
		{
			super();
			this.collegeBean = collegeBean;
			college_url=collegeBean.getCollege_url();
		}
		public Teacher getTeacher(String tid,String teaid,String code)
	    {
	        Map<Integer, List<Course>> cmap = sendPost(tid, teaid, code);

	        int j=0;
	        TeacherBean bean=new TeacherBean(collegeBean.getCollege_id(),collegeBean.getCollege_name(),tid,termMap.get(tid).getTermName(),teaid,teacherMap.get(teaid).getTeacherName());
	        Teacher teacher =new Teacher(bean);
	        teacher.getWeekList().clear();
	        if (cmap != null)
	        {
	            for (Map.Entry<Integer, List<Course>> l : cmap.entrySet()) {
	                //System.out.println(WEEK[j]);
	                System.out.println(l.getValue());
	                if(j>=7)
	                {
	                    break;
	                }
	                DayOfWeek weekDay=new DayOfWeek(WEEK[j]);
	                weekDay.setCourseList(l.getValue());
	                teacher.getWeekList().add(weekDay);
	               // System.out.println(weekDay.toString());
	                j++;
	            }

	            return teacher;
	        }
	        else
	        {
	            return null;
	        }
	    }
	    public List getIndex() {
	        try {
	            URL url = new URL(college_url+"/ZNPK/TeacherKBFB.aspx");
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            Map<String, List<String>> map = conn.getHeaderFields();
	            cookie = map.get("Set-Cookie").get(0);
	            InputStream in = conn.getInputStream();
	            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"gbk"));
	            StringBuilder builder = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                builder.append(line);
	            }
	            String index = builder.toString();
	            reader.close();
	            conn.disconnect();

	            Document doc = Jsoup.parse(index);
	            Elements elements = doc.select("select[name=\"Sel_XNXQ\"] option");
	            List<TermBean> termList = new ArrayList<TermBean>();
	            if(termMap!=null)
	            {
	            	termMap.clear();
	            }
	            for (Element element : elements) {
	                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
	                TermBean termBean=new TermBean(element.val(),element.html());
	              //  System.out.println(t);
	                termList.add(termBean);
	                termMap.put(element.val(), termBean);
	            }

	            return termList;

	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        return null;
	    }

	    // ???????? ????? ??? ?????????
	    public Map<Integer, List<Course>> sendPost(String termId, String tid, String code) {
	        try {
	            URL url = new URL(college_url+"/ZNPK/TeacherKBFB_rpt.aspx");
	            String param = "Sel_XNXQ=" + termId + "&Sel_JS=" + tid + "&type=" + 1 + "&txt_yzm=" + code;
	            // Connection con =
	            // Jsoup.connect("http://jwgl.lnc.edu.cn/ZNPK/TeacherKBFB_rpt.aspx");
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

	            conn.setRequestProperty("Cookie", cookie);
	            conn.setRequestProperty("Accept",
	                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
	            conn.setDoInput(true);
	            conn.setRequestMethod("POST");
	            conn.setDoOutput(true);
	            conn.setRequestProperty("User-Agent",
	                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36");
	            conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
	            conn.setRequestProperty("Referer", college_url+"/ZNPK/TeacherKBFB.aspx");
	            conn.setRequestProperty("Origin", college_url);
	            conn.setRequestProperty("Cache-Control", "max-age=0");

	            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
	            dos.writeBytes(param);
	            dos.flush();
	            dos.close();

	            InputStream in = conn.getInputStream();
	            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"gbk"));
	            StringBuilder builder = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                builder.append(line);
	            }
	            String info = builder.toString();
	            System.out.println(info);
	            if(info.contains(checkcode_error))
	            {
	                CODE_ERROR=1;
	                return null;
	            }
	            Document doc = Jsoup.parse(info);
	            Elements elements = doc.select("td");
	            elements.get(0);

	            Map<Integer, List<Course>> cmap = new LinkedHashMap<>();

	            List<Course> cl1 = new ArrayList<Course>();
	            List<Course> cl2 = new ArrayList<Course>();
	            List<Course> cl3 = new ArrayList<Course>();
	            List<Course> cl4 = new ArrayList<Course>();
	            List<Course> cl5 = new ArrayList<Course>();
	            List<Course> cl6 = new ArrayList<Course>();
	            List<Course> cl7 = new ArrayList<Course>();

	            cmap.put(1, cl1);
	            cmap.put(2, cl2);
	            cmap.put(3, cl3);
	            cmap.put(4, cl4);
	            cmap.put(5, cl5);
	            cmap.put(6, cl6);
	            cmap.put(7, cl7);

	            for (Element week : elements) {
	                if (week.html().equals(WEEK[0])) {
	                    Element wtr = week.parent();
	                    Elements trs = wtr.siblingElements();
	                    for (int j = 0; j < trs.size(); j++) {
	                        Element tr = trs.get(j);
	                        Elements trds = tr.children();
	                        int ncounter = 0;
	                        for (int i = 0; i < trds.size(); i++) {
	                            Element td = trds.get(i);

	                            if (td.attr("valign").equals("top")) {
	                                if (td.text() != null)
	                                    cmap.get(i - ncounter + 1).add(new Course(td.text() + ""));
	                                else
	                                    cmap.get(i - ncounter + 1).add(new Course(""));
	                            } else
	                                ncounter++;
	                        }
	                    }
	                    CODE_ERROR=0;
	                    return cmap;
	                }
	            }

	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        CODE_ERROR=0;
	        return null;

	    }
	    public byte[] getImageVer()
	    {
	    	
	    	InputStream in=null;
	    	HttpURLConnection conn=null;
	        try {
	        		URL url = new URL(college_url+"/sys/ValidateCode.aspx");
		            conn = (HttpURLConnection) url.openConnection();
		            conn.setRequestProperty("Cookie", cookie);
		            conn.setRequestProperty("Referer", college_url+"/ZNPK/TeacherKBFB.aspx");
		            in = conn.getInputStream();	            
		            byte[] buf = new byte[1024];
		            ByteArrayOutputStream baos=new ByteArrayOutputStream();
		            //定义整数类型对象
		            int number;
	            //利用循环方式将图片读完整
	            while((number=in.read(buf, 0, buf.length))>0)
	            {
	                baos.write(buf, 0, number);
	            }
	            //将字节保存到byte[]数组对象中
	            byte[] reallyByte = new byte[(baos.toByteArray()).length+1];
	            reallyByte=baos.toByteArray();
	            in.close();
	            conn.disconnect();
	            return reallyByte;
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	       return null;
	    }
	    public int getImage() {
	        //
	        FileOutputStream fo=null;
	        InputStream in=null;
	        HttpURLConnection conn=null;
	        try {
	            URL url = new URL(college_url+"/sys/ValidateCode.aspx");
	            conn = (HttpURLConnection) url.openConnection();
	            conn.setRequestProperty("Cookie", cookie);
	            conn.setRequestProperty("Referer", college_url+"/ZNPK/TeacherKBFB.aspx");
	             in = conn.getInputStream();
	             
	            File file = new File("D:/eclipse/jee-latest-released/workspace/sysedu/WebContent/codeImage.jpg");
	           //   /sysedu/image/codeImage.jpg
	         
	            fo = new FileOutputStream(file);
	            byte[] buf = new byte[1024];
	            int length = 0;
	            while ((length = in.read(buf, 0, buf.length)) != -1) {
	                fo.write(buf, 0, length);
	            }
	            return 1;
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        
	        }
	        finally
	        {
	            try
	            {
	                in.close();
	                fo.close();
	                conn.disconnect();
	            } catch (IOException e)
	            {
	                e.printStackTrace();
	            }
	            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	            System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
	            
	        }
	        return -1;
	    }



	    // ?????????
	    public List<TeacherBean> getTeachers(String term) {
	        try {
	            URL url = new URL(college_url+"/ZNPK/Private/List_JS.aspx?xnxq=" + term + "&t=276");
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setRequestProperty("Cookie", cookie);
	            InputStream in = conn.getInputStream();
	            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"gbk"));
	            StringBuilder builder = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                builder.append(line);
	            }
	            String info = builder.toString();

	            reader.close();
	            conn.disconnect();

	            Document doc = Jsoup.parse(info);
	            doc = Jsoup.parse(doc.select("script").html().substring(24));
	            Elements eles = doc.select("select[name=\"Sel_JS\"] option");
	            List<TeacherBean> slist = new ArrayList<>();
	            if(teacherMap!=null)
	            {
	            	teacherMap.clear();
	            }
	            for (Element element : eles) {
	                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
	               // slist.add(t);
	                TeacherBean teacherBean=new TeacherBean(element.val(),element.html());
	                slist.add(teacherBean);
	                teacherMap.put(element.val(), teacherBean);
	               // System.out.println(t);
	            }

	            return slist;

	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        return null;
	    }

	    public static String string2Unicode(String string) {

	        StringBuffer unicode = new StringBuffer();

	        for (int i = 0; i < string.length(); i++) {

	            // ??????????
	            char c = string.charAt(i);

	            // ????unicode
	            unicode.append("\\u" + Integer.toHexString(c));
	        }

	        return unicode.toString();
	    }

	    public String getCookie()
	    {
	        return cookie;
	    }

	    public void setCookie(String cookie)
	    {
	        this.cookie = cookie;
	    }
		@Override
		public Object get(String sid, String id, String code)
		{
			return getTeacher(sid, id, code);
		}
}
